import { Icon } from '@amcax/base';
import {
  ENV_FIELD_MAPPING,
  EnvCAD,
  useUserSettingCustomer,
} from '@app-base/common/providers/userSettingProvider';
import i18n from '@app-base/common/utils/i18next';
import { MessageTip } from '@app-base/common/utils/MessageTip';
import { CircleBarTableButtonItem } from '@app-base/common/widgets/CircleBar/types';
import { httpSettingApi } from '@app-base/server/setting-http';
import { Checkbox, Input, Select } from 'antd';
import { debounce } from 'lodash';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { SettingsPanel } from '../SettingsPanel';
import {
  getAllButtons,
  getFilteredButtonList,
} from '../../utils/filterHelpers';

const ENVIRONMENT_OPTIONS = [
  { value: 'part_env', label: 'settings.part_env' },
  { value: 'sketch_env', label: 'settings.sketch_env' },
  { value: 'product_env', label: 'settings.product_env' },
];

interface CommandConfigurationsProps {
  onCloseDialog?: () => void;
}

const CommandConfigurations: React.FC<CommandConfigurationsProps> = ({
  onCloseDialog,
}) => {
  const { hiddenCommandIds, setHiddenCommandIds, currentEnvironment } =
    useUserSettingCustomer();
  const [searchText, setSearchText] = useState('');
  const [environment, setEnvironment] =
    useState<keyof typeof EnvCAD>(currentEnvironment);
  const [uncheckedCommandNames, setUncheckedCommandNames] = useState<string[]>(
    [],
  );
  const [loading, setLoading] = useState(false);

  const allButtons = useMemo(() => getAllButtons(), []);

  const filteredButtonList = useMemo(() => {
    return getFilteredButtonList(allButtons, environment, searchText);
  }, [allButtons, environment, searchText]);

  const debouncedSetSearch = useCallback(
    debounce((value: string) => {
      setSearchText(value);
    }, 300),
    [],
  );

  const handleSearch = useCallback(
    (value: string) => {
      debouncedSetSearch(value);
    },
    [debouncedSetSearch],
  );

  // 初始化未选中的命令名称
  useEffect(() => {
    if (hiddenCommandIds && hiddenCommandIds[environment]) {
      setUncheckedCommandNames(hiddenCommandIds[environment]);
    } else {
      setUncheckedCommandNames([]);
    }
  }, [environment, hiddenCommandIds]);

  // 处理复选框变化
  const handleCheckboxChange = useCallback((name: string, checked: boolean) => {
    setUncheckedCommandNames((prev) => {
      if (checked) {
        return prev.filter((n) => n !== name);
      } else {
        return [...prev, name];
      }
    });
  }, []);

  // 转换为后端需要的驼峰命名格式
  const convertToBackendFormat = useCallback(
    (frontendData: Record<string, string[]>) => {
      const backendFormat = {};
      Object.keys(frontendData).forEach((key) => {
        const backendKey = ENV_FIELD_MAPPING[key];
        backendFormat[backendKey] = frontendData[key];
      });
      return backendFormat;
    },
    [],
  );

  // 恢复默认设置
  const resetToDefault = useCallback(() => {
    setUncheckedCommandNames([]);
    MessageTip.info('已恢复默认设置，保存后生效');
  }, []);

  // 处理保存
  const handleSave = useCallback(async () => {
    try {
      setLoading(true);
      // 更新本地状态
      const updatedFrozenCommands = {
        ...hiddenCommandIds,
        [environment]: uncheckedCommandNames,
      };

      const backendFormat = convertToBackendFormat(updatedFrozenCommands);

      await httpSettingApi.saveUserCmdConfigDetail({ ...backendFormat });

      setHiddenCommandIds(updatedFrozenCommands);
      MessageTip.success('保存成功');
    } catch (error) {
      console.error('保存命令配置失败:', error);
      MessageTip.error('保存失败');
    } finally {
      setLoading(false);
    }
  }, [
    environment,
    uncheckedCommandNames,
    hiddenCommandIds,
    setHiddenCommandIds,
    convertToBackendFormat,
  ]);

  const renderCommandItem = useCallback(
    (button: CircleBarTableButtonItem) => (
      <tr
        key={`${environment}-${button.name}-${button.id}`}
        className='h-[30px] border-b border-zinc-100'
      >
        <td className='align-top p-2'>{i18n.t(button.type)}</td>
        <td className='align-top p-2'>
          <Icon
            name={button.icon}
            size={16}
            className='mr-1 inline-block'
          />
          {i18n.t(button.label)}
        </td>
        <td className='align-top p-2 text-center'>
          <Checkbox
            checked={!uncheckedCommandNames.includes(button.id)}
            onChange={(e) => handleCheckboxChange(button.id, e.target.checked)}
            disabled={loading}
          />
        </td>
      </tr>
    ),
    [environment, uncheckedCommandNames, handleCheckboxChange, loading],
  );

  return (
    <SettingsPanel
      onSave={handleSave}
      onCancel={onCloseDialog}
      onRestoreDefaults={resetToDefault}
      isSaveDisabled={loading}
    >
      <div className='w-[560px]'>
        <div className='flex items-center h-[30px] mb-2.5'>
          <span className='mr-2 whitespace-nowrap'>
            {i18n.t('settings.environment')}：
          </span>
          <Select
            placeholder={i18n.t('settings.environment')}
            className='flex-1'
            value={environment}
            options={ENVIRONMENT_OPTIONS.map((option) => ({
              ...option,
              label: i18n.t(option.label),
            }))}
            onChange={setEnvironment}
            disabled={loading}
          />
        </div>

        <div className='flex items-center h-[30px] mb-2.5'>
          <span className='mr-2 whitespace-nowrap'>
            {i18n.t('settings.search')}：
          </span>
          <Input
            placeholder={i18n.t('settings.search')}
            className='flex-1'
            onChange={(e) => handleSearch(e.target.value)}
            disabled={loading}
          />
        </div>

        <div className='h-[360px] overflow-auto border border-zinc-200 rounded-md'>
          <table className='w-full select-none border-collapse'>
            <thead>
              <tr>
                <th className='sticky top-0 z-10 border-b border-zinc-200 bg-white p-2 text-left font-bold'>
                  {i18n.t('settings.type')}
                </th>
                <th className='sticky top-0 z-10 border-b border-zinc-200 bg-white p-2 text-left font-bold'>
                  {i18n.t('settings.command')}
                </th>
                <th className='sticky top-0 z-10 border-b border-zinc-200 bg-white p-2 text-center font-bold'>
                  {i18n.t('settings.visibility')}
                </th>
              </tr>
            </thead>
            <tbody>
              {filteredButtonList.length > 0 ? (
                filteredButtonList.map(renderCommandItem)
              ) : (
                <tr>
                  <td
                    colSpan={3}
                    className='text-center py-4 text-gray-500'
                  >
                    没有找到匹配的命令
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </SettingsPanel>
  );
};

export default CommandConfigurations;
